import os
import re


EXTS_LANG = {
    # C++
    'cpp': "c++",
    'CPP': "c++",
    'cc': "c++",
    'cxx': "c++",
    'c++': "c++",
    'cp': "c++",
    'C': "c++",
    'ii': "c++",

    # Object C++
    'mm': "objective-c++",
    'M': "objective-c++",
    'mii': "objective-c++",

    # C
    'c': "c",
    'i': "c",

    # Object C
    'm': "objective-c",
    'mi': "objective-c",
}

EXTS_HEADER = {
    # C/++, Object-C/++ header file ext
    'h',
    'hh',
    'H',
    'hp',
    'hxx',
    'hpp',
    'HPP',
    'h++',
    'tcc',
}

ARCHIVER_CACHE = {}


def is_assembly(f=""):
    ext = os.path.splitext(f)[1].strip('.').lower()
    if ext == 's':
        return True
    else:
        return False


def is_source(f=""):
    ext = os.path.splitext(f)[1].strip('.').lower()
    if EXTS_LANG.get(ext) is not None:
        return True
    else:
        return False

def is_header(f=""):
    ext = os.path.splitext(f)[1].strip('.').lower()
    if ext in EXTS_HEADER:
        return True
    else:
        return False


def check_language(file_name=""):
    ext = os.path.splitext(file_name)[1].strip('.').lower()
    lang = EXTS_LANG.get(ext, '')

    if not lang:
        return "c++"
    else:
        return lang


def is_archiver(c):
    if c in ARCHIVER_CACHE:
        return ARCHIVER_CACHE[c]

    proc = os.popen(c + " --version")
    result = proc.readlines()
    proc.close()

    if len(result) == 0:
        return False

    msg = result[0]

    res = True if 'GNU ar ' in msg else False
    ARCHIVER_CACHE[c] = res
    return res


def is_bitcode_file(file_name):
    is_bc = False

    with open(file_name, "rb") as f:
        chunk = f.read(2)
        if len(chunk) >= 2 and chunk[0] == 'B' and chunk[1] == 'C':
            is_bc = True

    return is_bc


def is_cpp_compiler(compiler):
    compiler_name = os.path.basename(compiler)
    return '++' in compiler_name or 'pp' in compiler_name


def is_non_x86_compiler(compiler):
    compiler_name = os.path.basename(compiler)
    return "aarch64" in compiler_name or "arm" in compiler_name or "mips" in compiler_name


def is_sharedlib(file_name):
    if re.match('.+\.so$', file_name)\
            or re.match('.+\.so\..+$', file_name):
        return True
    else:
        return False


def is_staticlib(file_name):
    if re.match('.+\.a$', file_name):
        return True
    else:
        return False


def is_objfile(file_name):
    if re.match('.+\.o$', file_name):
        return True
    else:
        return False

if __name__ == "__main__":
    print(is_header("/root/test_progs/lz4/programs/util.h"))